package copyengine.ui.dialog
{
	import copyengine.screenResize.CEScreenResizeManger;
	import copyengine.screenResize.IScreenResizeListener;
	import copyengine.utils.GeneralUtils;
	import copyengine.utils.debug.CELog;

	import flash.display.DisplayObjectContainer;
	import flash.display.Sprite;

	/**
	 * <b>Internal:: Hold在一组内Pop出来的所有DialogWarp</b>
	 * </br>当使用beginGroupCommand/endGroupCommand来PopCommand时候会将
	 * Group内的所有Dialog进行Warp,如果单独Pop一个Dialog,则每个Dialog封一个Warp后再封一个GroupPopWarp
	 */
	internal final class CEDialogGroupPopWarp implements IScreenResizeListener
	{
		private var allGroupPopVector:Vector.<CEDialogWarp>;
		private var groupPopWarpContainer:Sprite;
		private var dialogMangerContainer:DisplayObjectContainer;

		/**
		 *当前是否正在执行Dispose函数,
		 * 如果执行Dispose函数中,及不再响应onDisposeDialogCalled函数,以免多次操作Vector
		 */
		private var isDuringDispose:Boolean;

		/**
		 *当 当前的GroupPopWarp Dispose了以后的回调函数,
		 * 告知上层的CEDialogWarp删除其引用
		 */
		private var groupPopWarpDisposedCallBack:Function;

		public function CEDialogGroupPopWarp()
		{
		}

		//=============================================//
		//==                             Initialize&Dispose                                      ==//
		//=============================================//
		public function initialize(_groupPopWarpDisposedCallBack:Function, _dialogMangerContainer:DisplayObjectContainer):void
		{
			dialogMangerContainer = _dialogMangerContainer;
			groupPopWarpDisposedCallBack = _groupPopWarpDisposedCallBack;

			allGroupPopVector = new Vector.<CEDialogWarp>();
			groupPopWarpContainer = new Sprite();

			CEScreenResizeManger.instance.addScreenResizeListener(this);
		}

		public function dispose():void
		{
			isDuringDispose = true;
			for each (var dialogWarp:CEDialogWarp in allGroupPopVector)
			{
				dialogWarp.targetDialog.disposeDialog();
			}
			doDispose();
			isDuringDispose = false;
		}

		private function doDispose():void
		{
			CEScreenResizeManger.instance.removeScreenResizeListener(this);
			GeneralUtils.removeTargetFromParent(groupPopWarpContainer);
			groupPopWarpDisposedCallBack && groupPopWarpDisposedCallBack(this);
			groupPopWarpDisposedCallBack = null;
			allGroupPopVector = null;
			groupPopWarpContainer = null;
			dialogMangerContainer = null;
		}

		//============================================//
		//==                            Public Interface                                        ==//
		//============================================//

		public function addDialogWarp(_dialogWarp:CEDialogWarp):void
		{
			allGroupPopVector.push(_dialogWarp);
		}

		public function removeDialogWarp(_dialogWarp:CEDialogWarp):void
		{
			GeneralUtils.removeElementFromArrayOrVector(_dialogWarp, allGroupPopVector);
			allGroupPopVector.length > 0 ? doRefreshDialogModleWarp() : doDispose();
		}

		/**
		 * 清除当前PopWarp中在GroupCommand中被标记为删除的DialogWap
		 */
		public function removeAllMarkGroupDisposeTypeDialogWarp():void
		{
			for (var j:int = allGroupPopVector.length - 1; j >= 0; j--)
			{
				if (allGroupPopVector[j].groupCommandMarkType == CEDialogWarp.GROUP_COMMAND_MARK_TYPE_DISPOSE)
				{
					allGroupPopVector.splice(j, 1);
				}
			}
			allGroupPopVector.length > 0 ? doRefreshDialogModleWarp() : doDispose();
		}

		public function getDialogWarpByDialogUniqueName(_dialogUniqueName:String):CEDialogWarp
		{
			for each (var dialogWarp:CEDialogWarp in allGroupPopVector)
			{
				if (dialogWarp.targetDialog.getDialogUniqueName() == _dialogUniqueName)
				{
					return dialogWarp;
				}
			}
			return null;
		}

		public function show():void
		{
			dialogMangerContainer.addChild(groupPopWarpContainer);
			for each (var dialogWarp:CEDialogWarp in allGroupPopVector)
			{
				use namespace copyengine_dialog_internal;
				if (dialogWarp.targetDialog.getDialogState() == CEDialogConfig.STATE_NOT_OPEN)
				{
					//Pop新的Dialog
					dialogWarp.targetDialog.initDialog();
					//先将Dialog add到Stage上面,这样Dialog即可正常访问stage
					groupPopWarpContainer.addChild(dialogWarp.targetDialog.getDialogContainer());
					dialogWarp.targetDialog.popup();
					dialogWarp.targetDialog.setDialogState(CEDialogConfig.STATE_OPEN);
				}
				dialogWarp.targetDialog.refreshCallBackFunction(onSortCurrentDialogToTopCall, onDisposeDialogCalled);
			}
			layoutAllDialogByWarp();
			doRefreshDialogModleWarp();
		}

		public function getAllGroupPopVector():Vector.<CEDialogWarp>
		{
			return allGroupPopVector;
		}

		//============================================//
		//==                              Private Function                                     ==//
		//============================================//

		public function onScreenResize(_currenStageWidth:int,
									   _currentStageHeight:int,
									   _offestWidth:int,
									   _offestHeight:int,
									   _offsetXPercent:Number,
									   _offsetYPercent:Number):void
		{
			doRefreshDialogModleWarp();
			for each (var dialogWarp:CEDialogWarp in allGroupPopVector)
			{
				if (dialogWarp.targetDialog.getDialogState() == CEDialogConfig.STATE_OPEN)
				{
					dialogWarp.targetDialog.onScreenResize(_currenStageWidth,
														   _currentStageHeight,
														   _offestWidth,
														   _offestHeight,
														   _offsetXPercent,
														   _offsetYPercent);
				}
			}
		}

		/**
		 *如果当前处于Model模式中,Pop的Dialog中有一个Modle模式的Dialog则整个PopWarp处于模式中,
		 * 会在Contianr上面蒙上一层灰底(放置玩家点击底部元件)
		 */
		private function doRefreshDialogModleWarp():void
		{
			var isPopWarpInModel:Boolean = false;
			for each (var dialogWarp:CEDialogWarp in allGroupPopVector)
			{
				if (dialogWarp.isModal)
				{
					isPopWarpInModel = true;
					break;
				}
			}
			if (isPopWarpInModel)
			{
				groupPopWarpContainer.graphics.clear();
				groupPopWarpContainer.graphics.beginFill(0x999999, 0.3);
				groupPopWarpContainer.graphics.drawRect(0, 0, dialogMangerContainer.stage.stageWidth, dialogMangerContainer.stage.stageHeight);
				groupPopWarpContainer.graphics.endFill();
			}
			else
			{
				groupPopWarpContainer.graphics.clear();
			}
		}

		/**
		 * 当玩家点击Dialog后会将被点击的Dialog放到最高层,且把相应的GroupContainer也放置在最高层
		 * <b>注意!!!</b>
		 * </br>该函数是由CEDialog回调Warp,如果是由Dialog上面点击某个按钮(mouseDown)->触发清除屏幕上面所有Dialog
		 * ->当前Warp首先调用doDispose方法，然后在回调最后Dialog的mouseDown事件响应才会响应，此时已经dispose完成
		 */
		private function onSortCurrentDialogToTopCall(_dialogContainer:DisplayObjectContainer):void
		{
			groupPopWarpContainer && groupPopWarpContainer.addChild(_dialogContainer);
			dialogMangerContainer && dialogMangerContainer.addChild(groupPopWarpContainer);
		}

		/**
		 *<b>由Dialog回调当前的PopWarp</b>
		 * <li>如果是由PopWarp的Dispose函数触发的,则不作任何处理
		 * <li>如果是Dialog被用户的操作所关闭的则刷新当前的模式Warp或者Dispose掉当前的PopWarp
		 */
		private function onDisposeDialogCalled(_dialog:CEDialog):void
		{
			if (!isDuringDispose)
			{
				for (var i:int = 0; i < allGroupPopVector.length; i++)
				{
					if (allGroupPopVector[i].targetDialog == _dialog)
					{
						allGroupPopVector.splice(i, 1);
						break;
					}
				}
				allGroupPopVector.length > 0 ? doRefreshDialogModleWarp() : doDispose();
			}
		}

		/**
		 * 根据DialogWarp中的属性,Layout当前Dialog
		 */
		private function layoutAllDialogByWarp():void
		{
			allGroupPopVector.sort(sortDialogByRelativeCenterIndex);

			//当前Dialog的最左边PosX
			var currentDialogLetfPosX:int = (dialogMangerContainer.stage.stageWidth >> 1) - (getTotalDialogWidth() >> 1);
			for (var i:int = 0; i < allGroupPopVector.length; i++)
			{
				use namespace copyengine_dialog_internal;
				var dialog:CEDialog = allGroupPopVector[i].targetDialog;
				//需要对DialogContainer进行一个引用,否则直接调用dialog.getDialogContainer()取不到相应的属性，
				//也许和函数时internal有关?
				var dialogContainer:DisplayObjectContainer = dialog.getDialogContainer();
				if (allGroupPopVector[i].layoutType == CEDialogConfig.LAYOUT_TYPE_RELATIVE_CENTER)
				{
					dialogContainer.x = currentDialogLetfPosX + (dialogContainer.width >> 1);
					dialogContainer.y = dialogMangerContainer.stage.stageHeight >> 1;
					dialog.dialogContainerMoved();
					currentDialogLetfPosX += dialog.getDialogContainer().width;
				}
				else if (allGroupPopVector[i].layoutType == CEDialogConfig.LAYOUT_TYPE_ABSOLUTE_POS)
				{
					dialogContainer.x = allGroupPopVector[i].absolutePosX;
					dialogContainer.y = allGroupPopVector[i].absolutePosY;
					dialog.dialogContainerMoved();
				}
				else
				{
					CELog.err("CEDialogGroupPopWarp->layoutAllDialogByWarp unknow layout type: " + allGroupPopVector[i].layoutType);
				}


			}
		}

		private function sortDialogByRelativeCenterIndex(_a:CEDialogWarp, _b:CEDialogWarp):int
		{
			return _a.relativeCenterIndex < _b.relativeCenterIndex ? -1 : 1;
		}

		/**
		 * 取得场景上所有Dialog的总宽度
		 */
		private function getTotalDialogWidth():int
		{
			var totalWidth:Number = 0;
			for each (var dialogWarp:CEDialogWarp in allGroupPopVector)
			{
				use namespace copyengine_dialog_internal;
				totalWidth += dialogWarp.targetDialog.getDialogContainer().width;
			}
			return totalWidth;
		}

	}
}
